//
//  UIButton+Style.m
//  LuxuryGoods
//
//  Created by DCQ on 2018/6/21.
//  Copyright © 2018年 Future. All rights reserved.
//

#import "UIButton+Style.h"
 

@implementation UIButton (Style)
- (void)setupButtonContentType:(ButtonContentType) type{
    
    [self setupButtonContentType:type withSpacing:-9999];
}
- (void)setupButtonContentType:(ButtonContentType) type withSpacing:(CGFloat)spac  {
    self.titleLabel.backgroundColor = self.backgroundColor;
    self.imageView.backgroundColor = self.backgroundColor;
    
    if (type == ButtonContentType_imageRight) {
        
        //在使用一次titleLabel和imageView后才能正确获取titleSize
        CGSize titleSize = self.titleLabel.bounds.size;
        CGSize imageSize = self.imageView.bounds.size;
        CGFloat interval = 4.0;
        if (spac != -9999) {
            interval = spac;
        }
        
        
        self.imageEdgeInsets = UIEdgeInsetsMake(0,titleSize.width + interval, 0, -(titleSize.width + interval));
        self.titleEdgeInsets = UIEdgeInsetsMake(0, -(imageSize.width + interval), 0, imageSize.width + interval);
    }else if (type == ButtonContentType_imageCenter){
        
        // the space between the image and text
        CGFloat spacing = 4.0;
        if (spac != -9999) {
            spacing = spac;
        }
        // lower the text and push it left so it appears centered
        //  below the image
        CGSize imageSize = self.imageView.image.size;
        self.titleEdgeInsets = UIEdgeInsetsMake(
                                                  0.0, - imageSize.width, - (imageSize.height + spacing), 0.0);
        
        // raise the image and push it right so it appears centered
        //  above the text
        CGSize titleSize = [self.titleLabel.text sizeWithAttributes:@{NSFontAttributeName: self.titleLabel.font}];
        self.imageEdgeInsets = UIEdgeInsetsMake(
                                                  - (titleSize.height + spacing), 0.0, 0.0, - titleSize.width);
        
        // increase the content height to avoid clipping
        CGFloat edgeOffset = fabsf(titleSize.height - imageSize.height) / 2.0;
        self.contentEdgeInsets = UIEdgeInsetsMake(edgeOffset, 0.0, edgeOffset, 0.0);
        
    }
    
}
@end
